<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Flow;
use App\Models\Resume;
use App\Models\Step;
use App\Models\User;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Validator;

class StepController extends Controller {
	private $user;
	private $company_id;
	private $role_flag;
	public function __construct() {
		if (\Auth::guard('api')->check()) {
			$getUser = \Auth::guard('api')->user();
			$user = User::find($getUser->id);
			if (!$this->getDevice()) {
				//app
				$user->company_id = $user->appcompany_id;
			}
			$this->user = $user;
			$company = Company::find($this->user->company_id);
			$this->role_flag = $company->role_flag;
			$this->company_id = $user->company_id;
		}
	}
	//新增保存
	public function add(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		$roleType = $request->input('roleType');
		if ($roleType == 1) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('flow_add') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('flow_add')) {
					return $this->respond('no_auth');
				}
			}
			return $this->respond('op_ok');
		}
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('flow_add') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('flow_add')) {
				return $this->respond('no_auth');
			}
		}
		$flow_id = $request->input('flowId');
		if (empty($flow_id)) {
			return response()->json(['code' => 500, 'msg' => '流程id不能为空']);
		}
		$check_status = Resume::where(['company_id' => $this->company_id, 'flow_id' => $flow_id, 'status' => 0])->first();
		if (!empty($check_status)) {
			$get_status = DB::select('select id from resumes where step_id>=1 and company_id=? and ask_status!=2 and (check_status=0||check_status=3) and status=0 limit 1', [$this->company_id]);
			if (!empty($get_status)) {
				return response()->json(['code' => 500, 'msg' => '流程使用中,不能增加步骤！']);
			}
		}
		$validator = Validator::make($request->all(), Flow::$rules, Flow::$message);
		if ($validator->fails()) {
			return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
		}
		$m = new Step();
		$name = $request->input('name');
		$data = $m::where(['name' => $name, 'flow_id' => $flow_id, 'status' => 0])->first();
		if (!empty($data)) {
			return response()->json(['code' => 500, 'msg' => '步骤名称不能重复']);
		}
		$role_flag = Company::find($this->company_id)->role_flag;
		$time = time();
		$get_flow = Flow::find($flow_id);
		$msg1 = $name . '评价(' . $get_flow->name . ')';
		$msg2 = $name . '评价查看(' . $get_flow->name . ')';
		//开启事务
		DB::beginTransaction();
		try {
			$role_ids = 0;
			$role = Role::where(['name' => '管理员', 'type' => 1, 'is_delete' => 2, 'guard_name' => $role_flag])->first();
			if (!empty($role)) {
				$role_ids = $role->id;
			}
			//中间逻辑代码
			$sid = DB::table('steps')->insertGetId(['name' => $name, 'flow_id' => $flow_id, 'role_id' => $role_ids, 'created_at' => $time, 'updated_at' => $time]);
			$re1 = Permission::insert([
				['name' => "sys_step_op_" . $sid, 'guard_name' => $role_flag, 'alias' => $msg1, 'created_at' => $time, 'updated_at' => $time],
				['name' => "sys_step_view_" . $sid, 'guard_name' => $role_flag, 'alias' => $msg2, 'created_at' => $time, 'updated_at' => $time],
			]);
			DB::commit();
			return $this->respond('add_ok', Step::find($sid));
		} catch (\Exception $e) {
			//接收异常处理并回滚
			DB::rollBack();
			return $this->respond('add_error');
		}
	}
	//更新保存
	public function put(Request $request, $id, $type) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('flow_add') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('flow_add')) {
				return $this->respond('no_auth');
			}
		}
		if (!in_array($type, [1, 2])) {
			return response()->json(['code' => 500, 'msg' => '类型参数为空或无效']);
		}
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '步骤id不能为空']);
		}
		$m = new Step();
		$model = $m::find($id);
		if (empty($model)) {
			return $this->respond('get_error');
		}
		$check_status = Resume::where(['company_id' => $this->company_id, 'flow_id' => $model->flow_id, 'status' => 0])->first();
		if (!empty($check_status)) {
			$get_status = DB::select('select id from resumes where step_id>=1 and company_id=? and ask_status!=2 and (check_status=0||check_status=3) and status=0 limit 1', [$this->company_id]);
			if (!empty($get_status)) {
				$msg = $type == 2 ? '权限' : '';
				return response()->json(['code' => 500, 'msg' => '流程使用中,不能修改步骤' . $msg . '！']);
			}
		}
		if ($type == 1) {
			$validator = Validator::make($request->all(), Flow::$rules, Flow::$message);
			if ($validator->fails()) {
				return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
			}
			$name = $request->input('name');
			$data = $m::where(['name' => $name, 'flow_id' => $model->flow_id, 'status' => 0])->where('id', '!=', $id)->first();
			if (!empty($data)) {
				return response()->json(['code' => 500, 'msg' => '步骤名称不能重复']);
			}
			$model->name = $name;
			$role_flag = Company::find($this->user->company_id)->role_flag;
			$get_flow = Flow::find($model->flow_id);
			$msg1 = $name . '评价(' . $get_flow->name . ')';
			$msg2 = $name . '评价查看(' . $get_flow->name . ')';
			$time = time();
			//开启事务
			DB::beginTransaction();
			try {
				//中间逻辑代码
				$model->save();
				Permission::where('name', "sys_step_op_" . $id)->update(['alias' => $msg1, 'updated_at' => $time]);
				Permission::where('name', "sys_step_view_" . $id)->update(['alias' => $msg2, 'updated_at' => $time]);
				DB::commit();
				return $this->respond('update_ok');
			} catch (\Exception $e) {
				//接收异常处理并回滚
				DB::rollBack();
				return $this->respond('update_error');
			}
		}
		if ($type == 2) {
			$role_id = $request->input('roleId');
			/* $check_role = Role::where(['type' => 1, 'is_delete' => 2, 'status' => 0, 'guard_name' => $this->role_flag])->first();
				            if ($check_role->id == $role_id) {
				            return $this->respond('update_error');
			*/
			if (empty($role_id)) {
				return response()->json(['code' => 500, 'msg' => '角色id不能为空']);
			}
			$model->role_id = $role_id;
		}
		$result = $model->save();
		if ($result) {
			return $this->respond('update_ok');
		}
		return $this->respond('update_error');
	}
	//删除步骤,同时删除权限
	public function remove(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('flow_add') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('flow_add')) {
				return $this->respond('no_auth');
			}
		}
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '步骤id不能为空']);
		}
		$m = new Step();
		$model = $m::find($id);
		if (empty($model)) {
			return $this->respond('get_error');
		}
		$check_status = Resume::where(['company_id' => $this->company_id, 'flow_id' => $model->flow_id, 'status' => 0])->first();
		if (!empty($check_status)) {
			$get_status = DB::select('select id from resumes where step_id>=1 and company_id=? and ask_status!=2 and (check_status=0||check_status=3) and status=0 limit 1', [$this->company_id]);
			if (!empty($get_status)) {
				return response()->json(['code' => 500, 'msg' => '流程使用中,不能删除步骤！']);
			}
		}
		$model->status = 1;
		$time = time();

		$op_str = "sys_step_op_" . $id;
		$op_view = "sys_step_view_" . $id;
		DB::beginTransaction();
		try {
			//中间逻辑代码
			$model->save();
			Permission::where('name', $op_str)->update(['status' => 1, 'updated_at' => $time]);
			Permission::where('name', $op_view)->update(['status' => 1, 'updated_at' => $time]);
			//同步删除权限
			$get_per_id1 = Permission::where('name', $op_str)->pluck('id as permission_id');
			DB::table('role_has_permissions')->whereIn('permission_id', $get_per_id1)->delete();

			$get_per_id2 = Permission::where('name', $op_view)->pluck('id as permission_id');
			DB::table('role_has_permissions')->whereIn('permission_id', $get_per_id2)->delete();

			DB::commit();
			return $this->respond('delete_ok');
		} catch (\Exception $e) {
			//接收异常处理并回滚
			DB::rollBack();
			return $this->respond('delete_error');
		}
	}
	public function conclusion(Request $request) {
		$data = Config::get('info.conclusion_status');
		return $this->respond('get_ok', $data);
	}
	public function role() {
		$role_flag = $this->role_flag;
		$data = Role::where(['guard_name' => $role_flag, 'type' => 2, 'status' => 0])->orderBy('id', 'desc')->select('id', 'name')->get();
		return $this->respond('get_ok', $data);
	}
	public function get(Request $request, $id) {
		if (empty($id)) {
			return $this->respond('empty_error');
		}
		$m = new Step();
		$data = $m::where(['status' => 0, 'id' => $id])->select('role_id')->first();
		if (empty($data)) {
			return $this->respond('get_error');
		}
		return $this->respond('get_ok', $data);
	}
}
